package kyssion.leetcode.num51_100;

import java.util.ArrayList;
import java.util.List;

/**
 * 给定一个包含 m x n 个元素的矩阵（m 行, n 列），请按照顺时针螺旋顺序，返回矩阵中的所有元素。
 * <p>
 * 示例 1:
 * <p>
 * 输入:
 * [
 * [ 1, 2, 3 ],
 * [ 4, 5, 6 ],
 * [ 7, 8, 9 ]
 * ]
 * 输出: [1,2,3,6,9,8,7,4,5]
 * 示例 2:
 * <p>
 * 输入:
 * [
 * [1, 2, 3, 4],
 * [5, 6, 7, 8],
 * [9,10,11,12]
 * ]
 * 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
 */
public class code54_螺旋矩阵 {

    public static void main(String[] args) {
        System.out.println(new code54_螺旋矩阵().spiralOrder(
                new int[][]{
                }
        ));
    }

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if(matrix.length==0){
            return list;
        }
        int left = 0, top = 0;
        int right = matrix[left].length - 1, bottom = matrix.length - 1;
        while (left < right && top < bottom) {
            for (int a = left; a < right; a++) {
                list.add(matrix[top][a]);
            }
            for (int a = top; a < bottom; a++) {
                list.add(matrix[a][right]);
            }
            for (int a = right; a > left; a--) {
                list.add(matrix[bottom][a]);
            }
            for (int a = bottom; a > top; a--) {
                list.add(matrix[a][left]);
            }
            left++;right--;top++;bottom--;
        }

        if (left == right) {
            while(top<=bottom){
                list.add(matrix[top][left]);
                top++;
            }
        }else if(top==bottom){
            while(left<=right){
                list.add(matrix[top][left]);
                left++;
            }
        }
        return list;
    }
}
